package com.mobi.Survey.lib.model;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.http.ParseException;
import org.json.JSONException;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.mobi.Survey.lib.exceptions.AuthenticationException;
import com.mobi.Survey.lib.uicomponents.ControlFactory;
import com.mobi.Survey.lib.utils.Helper;

public class SurveysJsonParser {
	protected static JsonFactory jsonFactory = new JsonFactory();
	protected static SurveysJsonParser instance = null;

	protected SurveysJsonParser() {
	}

	public static synchronized SurveysJsonParser getInstance() {
		if (instance == null) {
			instance = new SurveysJsonParser();
		}
		return instance;
	}

	@SuppressWarnings("deprecation")
	public final List<SurveyPojo> isUser(InputStream is) throws JSONException, AuthenticationException {
		JsonParser jParser = null;
		try {
			if (is == null)
				return Collections.emptyList();
			if (jsonFactory == null)
				jsonFactory = new JsonFactory();
			jParser = jsonFactory.createJsonParser(is);
			return isUser(jParser);

		} catch (JsonParseException e) {

			e.printStackTrace();
			return Collections.emptyList();
		} catch (IOException e) {

			e.printStackTrace();
			return Collections.emptyList();
		} finally {
			try {
				jParser.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	protected void fillCoordinates(Address address) {

	}

	private final List<SurveyPojo> isUser(JsonParser jParser) throws JSONException, IOException,
			AuthenticationException {

		List<SurveyPojo> sps = new ArrayList<SurveyPojo>();
		while (jParser.getCurrentToken() != JsonToken.END_OBJECT) {
			jParser.nextToken();

			String fieldname = jParser.getCurrentName();
			String tokenValue = null;

			if (jParser.getCurrentToken() == JsonToken.START_ARRAY) {
				break;
			}
			if ("statusValue".equals(fieldname)) {
				jParser.nextToken();

				tokenValue = jParser.getText();
				if (null != tokenValue && tokenValue.trim().length() > 0)
					User.getInstance().setActive(Helper.toInt(tokenValue.trim()) == 1);

			} else if ("status".equals(fieldname)) {
				jParser.nextToken();
				tokenValue = jParser.getText();
				if (null != tokenValue && tokenValue.trim().length() > 0)
					User.getInstance().setUser("Successfully Login".equalsIgnoreCase(tokenValue.trim()));

			} else if ("Advertisement".equals(fieldname)) {
				jParser.nextToken();
				tokenValue = jParser.getText();
				if (null != tokenValue && tokenValue.trim().length() > 0)
					User.getInstance().setShowAds(Helper.toInt(tokenValue.trim()) == 1);

			} else if ("Image1".equals(fieldname)) {
				jParser.nextToken();
				tokenValue = jParser.getText();
				if (null != tokenValue && tokenValue.trim().length() > 0)
					User.getInstance().getListImage().setUrl(tokenValue.trim());

			} else if ("Image1Size".equals(fieldname)) {
				jParser.nextToken();
				tokenValue = jParser.getText();
				if (null != tokenValue && tokenValue.trim().length() > 0)
					User.getInstance().getListImage().setPercentHeight(Helper.toInt(tokenValue.trim()));

			}

			else if ("Image2".equals(fieldname)) {
				jParser.nextToken();
				tokenValue = jParser.getText();
				if (null != tokenValue && tokenValue.trim().length() > 0)
					User.getInstance().getDetailImage().setUrl(tokenValue.trim());

			}

			else if ("Image2Size".equals(fieldname)) {
				jParser.nextToken();
				tokenValue = jParser.getText();
				if (null != tokenValue && tokenValue.trim().length() > 0)
					User.getInstance().getDetailImage().setPercentHeight(Helper.toInt(tokenValue.trim()));

			} else if ("LayoutType".equals(fieldname)) {
				jParser.nextToken();
				tokenValue = jParser.getText();
				if (null != tokenValue && tokenValue.trim().length() > 0)
					User.getInstance().setLayoutType(Byte.parseByte(tokenValue.trim()));

			} else if ("LayoutName".equals(fieldname)) {
				jParser.nextToken();
				tokenValue = jParser.getText();
				if (null != tokenValue && tokenValue.trim().length() > 0)
					User.getInstance().setLayoutName(tokenValue.trim());

			}

		}

		if (User.getInstance().isActive() && User.getInstance().isUser()) {

			String fieldname = jParser.getCurrentName();
			String tokenValue = null;
			SurveyPojo survey = null;
			SubscriptionPojo sub = null;

			while (jParser.nextToken() != JsonToken.END_ARRAY) {
				fieldname = jParser.getCurrentName();
				if (jParser.getCurrentToken() == JsonToken.START_OBJECT) {
					survey = new SurveyPojo();
					sub = new SubscriptionPojo();

				}

				if (jParser.getCurrentToken() == JsonToken.END_OBJECT) {
					survey.setSubscription(sub);
					sps.add(survey);

				} else if ("Button1Value".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					if (null != tokenValue && tokenValue.trim().length() > 0)
						survey.settxtButtonInformation(tokenValue);
					// System.out.println(tokenValue);

				} else if ("Button2Value".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					if (null != tokenValue && tokenValue.trim().length() > 0)
						survey.setTxtBtnSurveyResult(tokenValue);
					// System.out.println(tokenValue);

				} else if ("Button3Value".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					if (null != tokenValue && tokenValue.trim().length() > 0)
						survey.setTxtBtnCorrectAnswer(tokenValue);
					// System.out.println(tokenValue);

				} else if ("Button4Value".equals(fieldname)) {

					jParser.nextToken();
					tokenValue = jParser.getText();
					if (null != tokenValue && tokenValue.trim().length() > 0) {
						survey.setTxtButtonTimer(tokenValue);
					}

				} else if ("CompanyEmail".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					if (null != tokenValue && tokenValue.trim().length() > 0) {
						survey.setSubsEmail(tokenValue);
						sub.setEmail(tokenValue);

					}// System.out.println(tokenValue);

				} else if ("CompanyName".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					survey.setCompanyName(tokenValue);
					// System.out.println(tokenValue);

				} else if ("EmailAddress".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					if (null != tokenValue && tokenValue.trim().length() > 0)
						survey.setContactEmail(tokenValue);
					// System.out.println(tokenValue);

				} else if ("FirstName".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					if (null != tokenValue && tokenValue.trim().length() > 0)
						sub.setfName(tokenValue);
					// System.out.println(tokenValue);

				} else if ("FormDescription".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					if (null != tokenValue && tokenValue.trim().length() > 0)
						survey.setSurveyDiscription(tokenValue);
					// System.out.println(tokenValue);

				} else if ("Phone".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					if (null != tokenValue && tokenValue.trim().length() > 0)
						survey.setPhone(tokenValue);
					// System.out.println(tokenValue);

				} else if ("FormId".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					long id = Long.parseLong(tokenValue);
					if (id == 0)
						throw new RuntimeException("Invalid Survey Id");
					survey.setId(id);

					// System.out.println(tokenValue);

				} else if ("FormKey".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					survey.setSurveyKey(tokenValue);
					// System.out.println(tokenValue);

				} else if ("iconUrl".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					if (null != tokenValue && tokenValue.trim().length() > 0)
						survey.setIconAddress(tokenValue);
					// System.out.println(tokenValue);

				} else if ("LastName".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					if (null != tokenValue && tokenValue.trim().length() > 0)
						sub.setlName(tokenValue);
					// System.out.println(tokeValue);

				} else if ("Mandatory".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();

					// System.out.println(tokeValue);

				} else if ("Pages".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					survey.setShowAllControls(Boolean.parseBoolean(tokenValue));
					// System.out.println(tokeValue);

				} else if ("rowCount".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					// System.out.println(tokeValue);

				} else if ("SeqNum".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();

					// System.out.println(tokeValue);

				} else if ("SubscriptionId".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					sub.setSubsId(Long.parseLong(tokenValue));
					survey.setSubscriptionId(Long.parseLong(tokenValue));

					// System.out.println(tokeValue);

				} else if ("Website".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					if (null != tokenValue && tokenValue.trim().length() > 0)
						survey.setWebsite(tokenValue);
					// System.out.println(tokeValue);

				} else if ("status".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					if (Integer.valueOf(jParser.getText()) != 1) {
						break;
					}

				} else if ("FontColor".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					if (null != tokenValue && tokenValue.trim().length() > 0)
						survey.setFontColor(tokenValue.trim());

				} else if ("BGColor".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					if (null != tokenValue && tokenValue.trim().length() > 0)
						survey.setbGColor(tokenValue);

				} else if ("BGImage".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					if (null != tokenValue && tokenValue.trim().length() > 0)
						survey.setbGImageUrl(tokenValue.trim());

				} else if ("StreetNumber".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					if (null != tokenValue && tokenValue.trim().length() > 0)
						survey.getAddress().setStreetNumber(tokenValue);

				} else if ("StreetName".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					if (null != tokenValue && tokenValue.trim().length() > 0)
						survey.getAddress().setStreetName(tokenValue);

				} else if ("City".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					if (null != tokenValue && tokenValue.trim().length() > 0)
						survey.getAddress().setCity(tokenValue);

				} else if ("State".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					if (null != tokenValue && tokenValue.trim().length() > 0)
						survey.getAddress().setState(tokenValue);

				} else if ("Country".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					if (null != tokenValue && tokenValue.trim().length() > 0)
						survey.getAddress().setCountry(tokenValue);

				} else if ("Zip".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					if (null != tokenValue && tokenValue.trim().length() > 0)
						survey.getAddress().setZip(tokenValue);

				}
			}

		} else {
			throw new AuthenticationException();
		}

		return sps;

	}

	@SuppressWarnings("deprecation")
	public final SurveyPojo parseSurveyDetailJson(InputStream json, long formId) throws IOException {

		JsonParser jParser = null;
		if (jsonFactory == null)
			jsonFactory = new JsonFactory();
		if (json != null) {
			jParser = jsonFactory.createJsonParser(json);

			final String SIZE_REGE = "\\d{1,2}(x|X)\\d{1,2}";

			String tokenValue = null;
			jParser.nextToken();
			SurveyPojo survey = new SurveyPojo();
			List<SurveyDetailPojo> surveyDetails = new ArrayList<SurveyDetailPojo>();
			List<AlarmPojo> alarms = new ArrayList<AlarmPojo>();

			SurveyDetailPojo surveyDetail = null;
			// while (JsonToken.START_ARRAY != jParser.getCurrentToken()) {
			// jParser.nextToken();
			// }

			do {
				jParser.nextToken();
				String fieldname = jParser.getCurrentName();

				if (jParser.getCurrentToken() == JsonToken.END_ARRAY) {
					survey.setAlarms(alarms);
					survey.setSurveyDetail(surveyDetails);
				}
				if (jParser.getCurrentToken() == JsonToken.START_OBJECT) {

					surveyDetail = new SurveyDetailPojo();

				}

				if (jParser.getCurrentToken() == JsonToken.END_OBJECT) {
					if (formId == surveyDetail.getSurveyId()) {
						// TODO remove BackGroundImage if
						// condition
						if (surveyDetail.getControlType() == ControlFactory.CONTROL_IMAGE_VIEW
								&& "BackGroundImage".equalsIgnoreCase(surveyDetail.getActualValue()))
							continue;

						// if control type is timer we will add
						// that
						// record in survey_alarm Table and will
						// create AlarmPojo object
						if (surveyDetail.getControlType() == ControlFactory.CONTROL_TIMER) {
							AlarmPojo alarm = new AlarmPojo(surveyDetail);

							if (alarm.isValidAlarm()) {
								alarms.add(alarm);
							}

						} else {

							surveyDetails.add(surveyDetail);
						}

					}

				}

				if ("ControlPara1".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					if (null != tokenValue && tokenValue.trim().length() > 0)
						surveyDetail.setControlParameter1(tokenValue);
					// System.out.println(tokenValue);

				} else if ("ControlPara2".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					if (null != tokenValue && tokenValue.trim().length() > 0)
						surveyDetail.setControlParameter2(tokenValue.trim());

				}

				else if ("ControlResult".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					if (null != tokenValue && tokenValue.trim().length() > 0)
						surveyDetail.setActualValue(tokenValue);
					// System.out.println(tokenValue);

				} else if ("ControlText".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					if (null != tokenValue && tokenValue.trim().length() > 0)
						surveyDetail.setControlText(tokenValue);
					// System.out.println(tokenValue);

				} else if ("ControlType".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					if (null != tokenValue && tokenValue.trim().length() > 0)
						surveyDetail.setControlType(Byte.parseByte(tokenValue));
					// System.out.println(tokenValue);

				} else if ("FormId".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					long fid = Long.parseLong(tokenValue);

					surveyDetail.setSurveyId(fid);
					// System.out.println(tokenValue);

				} else if ("Mandatory".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					if (null != tokenValue && tokenValue.trim().length() > 0)
						surveyDetail.setMendatory(Boolean.valueOf(tokenValue));
					// System.out.println(tokenValue);

				} else if ("rowCount".equals(fieldname)) {
					jParser.nextToken();
					if (null != tokenValue && tokenValue.trim().length() > 0)
						tokenValue = jParser.getText();
					// System.out.println(tokenValue); //

				} else if ("SeqNum".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					if (null != tokenValue && tokenValue.trim().length() > 0)
						surveyDetail.setSequanceNo(Integer.parseInt(tokenValue));
					// System.out.println(tokenValue); //

				} else if ("SubscriptionId".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();
					surveyDetail.setSubscriptionId(Long.parseLong(tokenValue));
					// System.out.println(tokenValue);

				} else if ("Size".equals(fieldname)) {
					jParser.nextToken();
					tokenValue = jParser.getText();

					if (null != tokenValue && tokenValue != "null" && tokenValue.length() > 0
							&& tokenValue.matches(SIZE_REGE)) {
						String[] size = tokenValue.split("x|X");
						surveyDetail.setPercentWidth(Helper.toFloat(size[0]));
						surveyDetail.setPercentHeight(Helper.toFloat(size[1]));

					}

				}

			} while (JsonToken.END_ARRAY != jParser.getCurrentToken());

			return survey;

		} else {
			throw new ParseException();
		}

	}
}